package com.nowcoder.community.config;

import com.nowcoder.community.quartz.AlphaJob;
import com.nowcoder.community.quartz.PostScoreRefreshJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2023/2/8 13:34
 * @Version java version 1.8
 */
//配置->数据库->调用
@Configuration
public class QuartzConfig {
    //FactoryBean可简化Bean的实例化过程
    //工厂设计模式

    /**
     * 配置JobDetail
     */
    //@Bean
    public JobDetailFactoryBean alphaJobDetail() {
        JobDetailFactoryBean jobBean = new JobDetailFactoryBean();
        jobBean.setJobClass(AlphaJob.class);
        jobBean.setName("alphaJob");
        jobBean.setGroup("alphaJobGroup");
        jobBean.setDurability(true);
        jobBean.setRequestsRecovery(true);
        return jobBean;
    }

    /**
     * 配置Trigger(SimpleTriggerFactoryBean,CroTriggerFactoryBean)
     * 这里的JobDetail对象是从上面配置的bean工厂里面取的
     */
    //@Bean
    public SimpleTriggerFactoryBean alphaTrigger(JobDetail alphaJobDetail) {
        SimpleTriggerFactoryBean triggerBean = new SimpleTriggerFactoryBean();
        triggerBean.setJobDetail(alphaJobDetail);
        triggerBean.setName("alphaTrigger");
        triggerBean.setGroup("alphaTriggerGroup");
        triggerBean.setRepeatInterval(3000);
        triggerBean.setJobDataMap(new JobDataMap());
        return triggerBean;
    }
/*****************以上仅用于测试用例，正式项目中将去掉@bean注解使其失效****************************/
    /**
     * 刷新帖子分数任务
     */
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setBeanName("postScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean triggerFactoryBean = new SimpleTriggerFactoryBean();
        triggerFactoryBean.setJobDetail(postScoreRefreshJobDetail);
        triggerFactoryBean.setBeanName("postScoreRefreshTrigger");
        triggerFactoryBean.setGroup("communityTriggerGroup");
        //每5分钟触发一次
        triggerFactoryBean.setRepeatInterval(1000 * 60 * 5);
        triggerFactoryBean.setJobDataMap(new JobDataMap());
        return triggerFactoryBean;
    }
}
